<script lang="ts">
    import { createUniqueId } from "../utils/createUniqueId";
    import type { MessageData } from "./Message";
    import Message from "./Message.svelte";
    import usezIndex from "../utils/usezIndex";

    let store = $state<MessageData[]>([]);
    let messageMap: any = $state({});
    let zindex = $state(0);

    const _close = (key: string) => {
        const item: undefined | MessageData = store.find((aitem: any) => {
            return aitem.key === key;
        });
        const items = store.filter((aitem: any) => {
            return aitem.key !== key;
        });
        store = items;

        delete messageMap[key];

        if (item) {
            item.onclose?.();
        }
    };
    export const close = (key: string) => {
        messageMap[key]?.hide();
    };
    export const open = (config: string | MessageData, type: "info" | "success" | "warning" | "error") => {
        if (typeof config === "string") {
            config = {
                content: config,
            };
        }
        if (!config.key) {
            config.key = createUniqueId();
        }
        config.type = type;
        zindex = usezIndex();
        store.push(config);
    };
    export const info = (config: string | MessageData) => {
        open(config, "info");
    };
    export const success = (config: string | MessageData) => {
        open(config, "success");
    };
    export const warning = (config: string | MessageData) => {
        open(config, "warning");
    };
    export const error = (config: string | MessageData) => {
        open(config, "error");
    };

    const className = $derived.by(() => {
        const hasStack = store.some((item) => {
            return item.stack;
        });
        return {
            "cm-messages-wrap": true,
            "cm-messages-wrap-stack": hasStack,
        };
    });
</script>

<div class={className} style={`z-index: ${zindex}`}>
    {#if store && store.length}
        {#each store as item, index (item.key)}
            <Message bind:this={messageMap[item.key!]} data={item} index={store.length - 1 - index} onclose={_close} />
        {/each}
    {/if}
</div>
